<template autoRoute="true">
  <div class="taskTypePage">
    <section class="top">
      <div class="title">任务类型</div>
      <div style="display: flex; gap: 12px">
        <el-input
          v-model="searchName"
          class="responsive-input"
          placeholder="请输入关键词搜索"
          :prefix-icon="Search"
          @change="handleSearch"
        />
        <el-button @click="handleAdd" type="primary" :icon="Plus"
          >添加类型</el-button
        >
      </div>
    </section>
    <div class="alert">
      💡任务类型用于配置该类型的生命周期及该类型任务需要的显示字段，以及自定义任务列表的字段排序，配置后对后续使用该类型的任务生效。
    </div>
    <div class="wbs-tree-container">
      <!-- 批量操作浮层 -->
      <CLBatchOpToolbar
        :show="showCLBatchOpToolbar"
        :selected-count="selectedRecords.length"
        @delete="handleBatchDelete"
      ></CLBatchOpToolbar>
      <!--   表格   -->
      <CLTable
        v-loading="loading"
        :router-fields="['statusFlag']"
        :fields="fields"
        :initial-data="tableData"
        :line-height="currentLineHeight"
        :more-actions="moreActions"
        :tableConfig="tableConfig"
        :page-query="tableDataQuery"
        @pagerChange="pagerChange"
        @onMoreAction="handleMoreAction"
        @show:records="handleShowRecords"
      >
      </CLTable>
      <!-- 字段配置悬浮层 -->
      <FieldConfigPopup
        :fields="currentFields"
        :position="fieldConfigPosition"
        :visible="showFieldConfig"
        @close="showFieldConfig = false"
        @fieldsChange="handleFieldsChange"
      />
    </div>
    <CDialog
      :title="operate === 'create' ? '新建' : '编辑'"
      v-model="dialogVisible"
      @handleDialogOk="handleCreateOrEdit"
      :fields="dialogFields"
      :nodeData="selectedNode"
    ></CDialog>
  </div>
</template>
<script setup lang="ts">
  import { Plus, Search } from "@element-plus/icons-vue";
  import { ElInput, ElMessage, ElMessageBox } from "element-plus";
  import { onMounted, provide, reactive, ref } from "vue";
  import CLBatchOpToolbar from "@/components/CLBatchOpToolbar.vue";
  import CLTable from "@/components/CLTable/index.vue";
  import type { DynamicField } from "@/data/wbsFields.ts";
  import FieldConfigPopup from "@/components/FieldConfigPopup.vue";
  import { tableFields, dialogCreateOrEditFields } from "./fields/index.ts";
  import { useRouter } from "vue-router";
  import CDialog from "@/components/CDialog.vue";
  import type {
    createTaskTypeParamsType,
    listQueryType,
    taskResultVo,
  } from "@/interface/pm/globalTaskType.ts";
  import {
    createTaskType,
    deleteTaskType,
    deleteTaskTypeBatch,
    getTaskTypeList,
    updateTaskType,
  } from "@/api/pm/globalTaskType.ts";
  import { deepCopy } from "@/utils/common.ts";
  import { updateProjectType } from "@/api/pm/globalProjectTask.ts";

  const searchName = ref("");
  const loading = ref(false);
  const router = useRouter();

  // 批量操作
  const showCLBatchOpToolbar = ref(false);
  const selectedRecords = ref<any[]>([]);
  // 处理批量删除操作
  const handleBatchDelete = () => {
    console.log("selectedRecords", selectedRecords.value);
    if (selectedRecords.value.length === 0) return;
    ElMessageBox.confirm("确定删除该任务类型?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      // type: "warning",
      draggable: true,
    })
      .then(async () => {
        await deleteTaskTypeBatch(selectedRecords.value.map((item) => item.id));
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        getTableData();
      })
      .catch(() => {});
    // 删除完成后清空选中状态
  };

  // 表格
  const fields = ref<DynamicField[]>(tableFields); // table表格展示列
  const tableData = ref<taskResultVo[]>([]);
  // 当前行高设置
  const currentLineHeight = ref<"low" | "medium" | "high" | "ultra-high">(
    "low",
  );
  const moreActions = ref([
    { key: "setting", label: "配置类型" },
    { key: "edit", label: "编辑" },
    { key: "delete", label: "删除" },
  ]);
  const tableConfig = ref({
    editable: false,
    borderMode: "none",
    tableH: "calc(100vh - 150px)",
    showOperationsColumn: true, // 是否显示操作列
    OperationsColumnMode: "textIcon", // 操作列模式，text为文本模式
    // OperationsColumnWidth: 10, //自定义操作列宽度
    frozenColCount: 0, // 冻结前面列数
    rightFrozenColCount: 0, // 冻结后面列数
    page: {
      enable: true,
    },
    // tree: {
    //   enabled: true, // 开启树形结构
    //   column: 2, // 开启的树形结构的列索引
    //   mode: "wbs", // 开启wbs模式
    // },
    // rowSeriesNumber: {
    //   dragOrder: true, // 开启行号拖拽排序
    // },
    // borderMode: "none", // 表格边框模式，none为无边框
  });

  const pagerChange = (pager: { currentPage: number; pageSize: number }) => {
    tableDataQuery.pageNo = pager.currentPage;
    tableDataQuery.pageSize = pager.pageSize;
    getTableData();
  };

  const handleSearch = () => {
    tableDataQuery.conditions!.push({
      field: "name",
      operator: "like",
      value: searchName.value,
    });
    getTableData();
  };

  const handleMoreAction = async (action: string, node: any) => {
    if (action === "edit") {
      selectedNode.value = deepCopy(node);
      selectedNode.value.name = selectedNode.value?.name?.zh_CN;
      dialogVisible.value = true;
      operate.value = "edit";
    } else if (action === "delete") {
      ElMessageBox.confirm("确定删除该任务类型?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true,
      })
        .then(async () => {
          await deleteTaskType(node.id!);
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          await getTableData();
        })
        .catch(() => {});
    } else if (action === "setting") {
      router.push(
        `/pm/globalSetting/taskTypeDetail?taskTypeName=${node.name.zh_CN}&id=${node.id}`,
      );
    } else if (action === "statusFlag") {
      const params: createTaskTypeParamsType = {
        id: node.id,
        status: node.status === "NORMAL" ? "DISABLE" : "NORMAL",
      };
      await updateTaskType(params);
      ElMessage({
        type: "success",
        message: "编辑成功",
      });
      await getTableData();
    }
  };
  const handleShowRecords = (records: any[]) => {
    console.log("handleShowRecords", records);
    selectedRecords.value = records;
    showCLBatchOpToolbar.value = records.length > 0;
  };

  // 配置字段
  const currentFields = ref<DynamicField[]>([]);
  const fieldConfigPosition = ref({ left: 0, top: 0 });
  const showFieldConfig = ref(false);

  // 处理字段配置变化
  const handleFieldsChange = (updatedFields: DynamicField[]) => {
    // 更新本地字段配置，确保拖拽后能同步显示
    currentFields.value = JSON.parse(JSON.stringify(updatedFields));
    console.log("字段配置已更新:", updatedFields);
    fields.value = [...updatedFields];
  };

  // 显示字段配置弹窗
  const showFieldConfigPopup = (position: { left: number; top: number }) => {
    fieldConfigPosition.value = position;
    currentFields.value = JSON.parse(JSON.stringify(fields.value || []));
    setTimeout(() => {
      showFieldConfig.value = !showFieldConfig.value;
    }, 100);
  };
  // const addRecord = (newRecords: ProjectNode[]) => {
  //   tableData.value = [...newRecords];
  // };
  //
  // // 提供给所有子孙组件使用
  // provide("addRecord", addRecord);
  provide("showFieldConfigPopup", showFieldConfigPopup);

  // 弹框
  const dialogFields = ref<DynamicField[]>(dialogCreateOrEditFields);
  const dialogVisible = ref(false);
  const operate = ref("create");
  const selectedNode = ref<taskResultVo>({} as taskResultVo);

  const handleCreateOrEdit = async (formData: Record<string, any>) => {
    // console.log(formData, "handleCreateLifecycle");
    if (operate.value === "create") {
      const params: createTaskTypeParamsType = {
        name: {
          zh_CN: formData.name,
        },
        remark: formData.remark,
      };
      await createTaskType(params);
      ElMessage({
        type: "success",
        message: "添加成功",
      });
      dialogVisible.value = false;
      await getTableData();
    } else if (operate.value === "edit") {
      const params: createTaskTypeParamsType = {
        id: formData.id,
        name: {
          zh_CN: formData.name,
        },
        remark: formData.remark,
      };
      await updateTaskType(params);
      ElMessage({
        type: "success",
        message: "编辑成功",
      });
      dialogVisible.value = false;
      await getTableData();
    }
  };

  const handleAdd = () => {
    dialogVisible.value = true;
    operate.value = "create";
  };

  const tableDataQuery = reactive<listQueryType>({
    pageNo: 1,
    pageSize: 10,
    total: 0,
  });
  const getTableData = async () => {
    loading.value = true;
    const res = await getTaskTypeList(tableDataQuery);
    tableDataQuery.total = res.total;
    tableData.value =
      res.result?.map((item) => {
        item.statusFlag = item.status === "NORMAL";
        return item;
      }) || [];
    selectedRecords.value = [];
    tableDataQuery.conditions = [];
    loading.value = false;
  };

  onMounted(() => {
    getTableData();
  });
</script>

<style scoped lang="scss">
  .taskTypePage {
    padding: 16px 16px 0 16px;
    .top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      .title {
        font-weight: 500;
        font-size: 18px;
        line-height: 22px;
      }
    }
    .alert {
      height: 32px;
      background: #fff3eb;
      display: flex;
      align-items: center;
      color: #5e5e5e;
      font-size: 14px;
      padding: 0 12px;
      margin-bottom: 14px;
    }
    .wbs-tree-container {
      background-color: #fff;
      position: relative;
    }
  }
</style>
